package com.atguigu.tingshu.order.receiver;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.order.mapper.LocalMsgMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.sql.Struct;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/2/12
 */
@Component
public class OrderInfoReceiver {

    @Autowired
    private LocalMsgMapper localMsgMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;


    /**
     * 监听本地消息表，进行修改
     * @param content
     * @param message
     * @param channel
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_LOCAL_MSG),
            exchange = @Exchange(value = MqConst.EXCHANGE_LOCAL_MSG),
            key = MqConst.ROUTING_LOCAL_MSG
    ))
    @SneakyThrows
    public void listenLocalMsg(String content, Message message, Channel channel){
        if (StringUtils.isEmpty(content)){
            return;
        }
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            localMsgMapper.updateLocalMsg(content);
            channel.basicAck(deliveryTag,false);
        } catch (Exception e) {
            throw new GuiguException(201,"修改本地消息表失败");

        }
    }


    @RabbitListener(queues = MqConst.QUEUE_CANCEL_ORDER)
    @SneakyThrows
    public void listenCancelOrder(String content, Message message, Channel channel){
        if (StringUtils.isEmpty(content)){
            return;
        }

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {

            orderInfoMapper.cancelOrder(content);
            channel.basicAck(deliveryTag,false);

        } catch (Exception e) {
            throw new GuiguException(201,"修改取消订单状态失败");

        }
    }



}